package com.jia.together.controller.front;

import com.alibaba.fastjson.JSON;
import com.jia.together.entity.Blog;
import com.jia.together.entity.Course;
import com.jia.together.entity.Resource;
import com.jia.together.service.BlogService;
import com.jia.together.service.CourseService;
import com.jia.together.service.ResourceService;
import com.jia.together.utils.R;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/front/elastic")
public class ElasticSearchController {

    public static final String ELASTIC_SEARCH_INDEX = "running_together";

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private CourseService courseService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private ResourceService resourceService;

    @GetMapping("/delete/{name}")
    public R delElastic (@PathVariable String name) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(name);
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        return R.ok();
    }

    @GetMapping("/addCourse")
    public R addCourse() throws IOException {
        List<Course> courseList = courseService.list(null);
        BulkRequest request = new BulkRequest();
        request.timeout("120s");
        for (int i = 0; i < courseList.size(); i++) {
            request.add(
                    new IndexRequest("running_together")
                            .source(JSON.toJSONString(courseList.get(i)), XContentType.JSON)
            );
        }

        BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(bulk.hasFailures());
        return R.ok();
    }

    @GetMapping("/addBlog")
    public R addBlog() throws IOException {
        List<Blog> blogList = blogService.list(null);
        BulkRequest request = new BulkRequest();
        request.timeout("120s");
        for (int i = 0; i < blogList.size(); i++) {
            request.add(
                    new IndexRequest("running_together")
                            .source(JSON.toJSONString(blogList.get(i)), XContentType.JSON)
            );
        }

        BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        return R.ok();
    }

    @GetMapping("/addResource")
    public R addResource() throws IOException {
        List<Resource> resourceList = resourceService.list(null);
        BulkRequest request = new BulkRequest();
        request.timeout("120s");

        for (int i = 0; i < resourceList.size(); i++) {
            request.add(
                    new IndexRequest("running_together")
                            .source(JSON.toJSONString(resourceList.get(i)), XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        return R.ok();
    }

    @GetMapping("/search")
    public R search(@RequestParam String key,@RequestParam int pageNum,@RequestParam int pageSize) throws IOException {
        if (pageNum <= 1){
            pageNum = 1;
        }
        int page = (pageNum-1) * pageSize + 1;

        // 条件构建
        SearchRequest searchRequest = new SearchRequest(ELASTIC_SEARCH_INDEX);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(page);
        sourceBuilder.size(pageSize);
//        TermQueryBuilder builder = QueryBuilders.termQuery("title", key);
//        MultiMatchQueryBuilder builder = QueryBuilders.multiMatchQuery(key,  "description","title");
        QueryStringQueryBuilder builder = QueryBuilders.queryStringQuery(key);
        sourceBuilder.query(builder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 执行查询
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        long total = searchResponse.getHits().getTotalHits().value - 1;
        // 解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            list.add(sourceAsMap);
        }
        return R.ok().data("data",list).data("total",total);
    }

}
